/**
 * 根据域名判断当前环境状态
 */

import JSZip from 'jszip'
import Lottie from 'lottie-web'

export function getEnv() {
  return process.env
}

// 获取 url 里的 query
export function getQuery(name, search) {
  const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`, 'i')
  const source = search || window.location.search
  const r = source.substr(1).match(reg)
  if (r !== null) {
    // sessionStorage.setItem('token', unescape(r[2]))
    return unescape(r[2])
  }
  return null
}

/**
 * 获取 app user_agent 里的鉴权信息
 * @param {String} type 特定值
 */
export function getAuthentication(type) {
  const reg = new RegExp(`${type}/([\\w._-]+)\\s?`, 'i')
  const res = navigator.userAgent.match(reg)
  if (res && res.length === 2) {
    return res[1]
  }
  return null
}

export function getVersion() {
  return getAuthentication('amAppVersion')
}

export function isWechat() {
  return /MicroMessenger/i.test(window.navigator.userAgent)
}

export function isIOS() {
  return /(iphone|ipad|ipod|ios)/i.test(window.navigator.userAgent.toLocaleLowerCase())
}

export function compareVersions(version1, version2) {
  // 去除预发布标识符和构建元数据
  version1 = version1?.replace(/-.*$/, '').replace(/\+.*$/, '')
  version2 = version2?.replace(/-.*$/, '').replace(/\+.*$/, '')

  // 将版本号字符串转换为数字数组
  const arr1 = version1?.split('.').map(Number)
  const arr2 = version2?.split('.').map(Number)

  // 比较每一位数字
  for (let i = 0; i < Math.max(arr1.length, arr2.length); i++) {
    const num1 = arr1[i] || 0
    const num2 = arr2[i] || 0

    if (num1 < num2) {
      return -1
    } else if (num1 > num2) {
      return 1
    }
  }

  return 0
}

/**
 * 核心代码看这里
 * @param zipSrc 远端的链接
 */
export const unZipLottieFile = async (zipSrc) => {
  /**
   * 加载zip文件 并用 arrayBuffer 读取，arraybuffer 即不带view的 二进制数据
   */
  const zipBuffer = await fetch(zipSrc).then((response) => response.arrayBuffer())

  /**
   * 使用 jsZip 读取文件
   */
  const zip = await JSZip.loadAsync(zipBuffer)

  // 打印一下给大家看下这个里的结构
  console.log('[zip]', zip)

  const imageUrlsMap = {}
  let oriJson = {}

  for (let zipEntry of Object.values(zip.files)) {
    // 跳过文件夹 和 隐藏文件
    if (zipEntry.dir || /\/\./.test(zipEntry.name)) {
      continue
    }

    const isJSON = /\.json/i.test(zipEntry.name)
    const isImg = /\.(jpg|jpeg|png|gif)$/i.test(zipEntry.name)

    if (isJSON) {
      // 获取 核心的 JSON 配置文件
      const oriJsonText = await zipEntry.async('text')
      if (oriJsonText) {
        oriJson = JSON.parse(oriJsonText)
      }
    } else if (isImg) {
      // 图片以 blob方式读取
      const imgBlob = await zipEntry.async('blob')
      const fileName = zipEntry.name.split('/').pop()
      // 转成 临时的 URL
      imageUrlsMap[fileName] = URL.createObjectURL(new Blob([imgBlob]))
    }
  }

  /**
   * 定义一个辅助方法替换图片路径
   * @param obj
   * @returns
   */
  function deepUpdateImgPath(obj) {
    if (typeof obj !== 'object' || obj === null) {
      return obj
    }

    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        if (key === 'p') {
          if (imageUrlsMap[obj[key]]) {
            const filePath = imageUrlsMap[obj[key]]
            obj[key] = filePath.split('/').pop()
          }
        } else {
          obj[key] = deepUpdateImgPath(obj[key])
        }
      }
    }

    return obj
  }

  // 替换JSON 内的 assets 内的 p 属性为 临时路径
  const targetJSON = deepUpdateImgPath(oriJson)
  return {
    json: targetJSON,
    imageUrlsMap
  }
}

export const loadZipAnimation = async (src, domStr) => {
  const { json } = await unZipLottieFile(src)
  console.log(json)
  Lottie.loadAnimation({
    container: document.getElementById(domStr || 'lottie'),
    renderer: 'svg',
    loop: true,
    autoplay: true,
    // 这里要修改为这个
    assetsPath: `blob:${window.location.origin}/`,
    animationData: JSON.parse(JSON.stringify(json))
  })
}

export const subPackageConfig = () => {
  const name = getAuthentication('package') || getQuery('package') || 'ameng'
  let baseConfig = {
    package_name: '',
    coin_name: '',
    package_key: '',
    version: '',
    baseUrl: '',
    package_subName: ''
  }
  switch (name) {
    case 'ameng':
      baseConfig = {
        package_name: '爱萌岛',
        package_subName: '爱萌',
        coin_name: '爱Dou',
        package_key: 'ameng',
        version: getVersion(),
        baseUrl: '//www.aimengtec.com'
      }
      break
    case 'ymeng':
      baseConfig = {
        package_name: '元萌之声',
        package_subName: '元萌',
        coin_name: '萌Dou',
        package_key: 'ymeng',
        version: getVersion(),
        baseUrl: '//ym.aimengtec.com'
      }
      break
    default:
      baseConfig = {
        package_name: '爱萌岛',
        package_subName: '爱萌',
        coin_name: '爱Dou',
        package_key: 'ameng',
        version: getVersion(),
        baseUrl: '//www.aimengtec.com'
      }
      break
  }
  console.log(`当前包信息`, window.baseConfig)
  window.baseConfig = baseConfig
  return baseConfig
}
